import { useEffect, useState } from 'react';
import HeaderAndNav from './HeaderAndNav';
import Articles from './Articles';
import HistoricalArticles from './HistoricalArticles';
import ThemeToggle from './ThemeToggle'; // Import the new ThemeToggle component
import { login, fetchArticles } from '../api/api';
import { useAuth } from '../context/AuthContext';

export default function Component() {
  const [articles, setArticles] = useState([]);
  const [error, setError] = useState(null);
  const [theme, setTheme] = useState('default');
  const { setToken } = useAuth();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = await login(setToken);
        const articlesData = await fetchArticles(token);
        setArticles(articlesData);
      } catch (error) {
        console.error('Error fetching articles:', error);
        setError('无法加载文章数据，请稍后重试。');
      }
    };

    fetchData();
  }, [setToken]);

  return (
    <div className={`min-h-screen ${theme === 'dark' ? 'bg-black text-white' : 'bg-gray-100 text-black'}`}>
      <ThemeToggle theme={theme} onThemeChange={setTheme} />
      <HeaderAndNav theme={theme} />
      <div className="flex flex-col md:flex-row justify-center">
        <div className="w-full md:w-[80%] flex flex-col md:flex-row">
          {error ? (
            <p className="text-center text-red-500">{error}</p>
          ) : (
            <Articles articles={articles} theme={theme} />
          )}
          <HistoricalArticles theme={theme} />
        </div>
      </div>
    </div>
  );
}
